﻿using Interface.Core.Controllers;
using Interface.Core.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Interface.Mvc.Areas.Scrm.Controllers
{
    public class StoreController : CoreController
    {
        Random rd = new Random();

        /// <summary>
        /// 根据门店编号获取门店信息
        /// url: /scrm/store/getdealerbycode
        /// params: code
        /// </summary>
        [HttpGet]
        public string GetDealerByCode(string code)
        {
            string sql = @"select KeyId,Usecode,DealerName,DealerAddress,lat,lng,Milk,Food,LineCode from Sys_V_Dealer where usecode = @code";

            var entity = db.Crm.Query<dynamic>(sql, new { code }).FirstOrDefault();

            return ResultUtility.UnknownResult(entity != null, data: entity);
        }

        /// <summary>
        /// 根据导购手机号码获取所在门店
        /// url: /scrm/store/getdealerbyguidemobile
        /// params: mobile
        /// </summary>
        [HttpGet]
        public string GetDealerByGuideMobile(string mobile)
        {
            string sql = @"select t2.KeyId,t2.Usecode,t2.DealerName,t2.DealerAddress 
                from Sys_ShoppingGuideDtl(nolock) as t1
                inner join Sys_V_Dealer(nolock) as t2 on t2.keyid = t1.skeyid 
                inner join Sys_ShoppingGuide(nolock) as t3 on t3.keyid = t1.mkeyid
                where t3.mobile = @mobile";

            var list = db.Crm.Query<dynamic>(sql, new { mobile });

            return ResultUtility.SuccessResult(data: list.ToList());
        }

        /// <summary>
        /// 导购注册
        /// url: /scrm/store/guideregister
        /// params: mobile, name, wxid, skeyid
        /// </summary>
        [HttpPost]
        public string GuideRegister(string mobile, string name, string wxid, int skeyid)
        {
            string sql = @"select keyid,wxid from Sys_ShoppingGuide(nolock) where mobile = @mobile";

            var user = db.Crm.Query<dynamic>(sql, new { mobile }).FirstOrDefault();

            int userid = 0;

            db.Crm.BeginTransaction();

            if (user != null)
            {
                userid = user.keyid;

                if (string.IsNullOrEmpty(user.wxid))
                {
                    sql = @"update Sys_ShoppingGuide set name=@name,wxid=@wxid,updatetime=@time where keyid=@userid";
                    db.Crm.Execute(sql, new { name, wxid, time = DateTime.Now, userid });
                }
            }
            else
            {
                sql = @"insert into Sys_ShoppingGuide(Mobile,iPassword,Name,Effective,WxID,InsertTime,UpdateTime,InsertID) 
                    values(@mobile,@pwd,@name,@effective,@wxid,@insertTime,@updateTime,@insertid);SELECT CAST(SCOPE_IDENTITY() as int)";
                var obj = new
                {
                    mobile,
                    pwd = rd.Next(100000, 999999).ToString(),
                    name,
                    effective = true,
                    wxid,
                    inserttime = DateTime.Now,
                    updatetime = DateTime.Now,
                    insertid = 1
                };
                userid = Enumerable.FirstOrDefault(db.Crm.Query<int>(sql, obj));
            }

            sql = @"select count(1) from Sys_ShoppingGuideDtl(nolock) where mkeyid = @userid and skeyid = @skeyid";

            int count = db.Crm.Query<int>(sql, new { userid, skeyid }).FirstOrDefault();

            if (count == 0)
            {
                sql = @"insert into Sys_ShoppingGuideDtl(MKeyid,SKeyid,Effective) values(@userid,@skeyid,@effective)";
                db.Crm.Execute(sql, new { userid, skeyid, effective = true });
            }

            db.Crm.Commit();

            return ResultUtility.SuccessResult();
        }

        /// <summary>
        /// 导购添加所在门店
        /// url: /scrm/store/guideaddstore
        /// params: mobile, skeyid
        /// </summary>
        [HttpPost]
        public string GuideAddStore(string mobile, int skeyid)
        {
            string sql = @"select keyid,wxid from Sys_ShoppingGuide(nolock) where mobile = @mobile";

            var user = db.Crm.Query<dynamic>(sql, new { mobile }).FirstOrDefault();

            if (user != null)
            {
                int userid = user.keyid;

                sql = @"select count(1) from Sys_ShoppingGuideDtl(nolock) where mkeyid = @userid and skeyid = @skeyid";

                int count = db.Crm.Query<int>(sql, new { userid, skeyid }).FirstOrDefault();

                if (count == 0)
                {
                    sql = @"insert into Sys_ShoppingGuideDtl(MKeyid,SKeyid,Effective) values(@userid,@skeyid,@effective)";
                    db.Crm.Execute(sql, new { userid, skeyid, effective = true });
                }

                return ResultUtility.SuccessResult();
            }

            return ResultUtility.FailureResult("导购身份不存在!");
        }
        
        /// <summary>
        /// 查看导购是否有效
        /// url: /scrm/store/guideisok
        /// params: mobile
        /// </summary>
        [HttpGet]
        public string GuideIsOk(string mobile)
        {
            string sql = @"select keyid from Sys_ShoppingGuide(nolock) where mobile = @mobile";

            var user = db.Crm.Query<dynamic>(sql, new { mobile }).FirstOrDefault();

            if (user != null)
            {
                return ResultUtility.SuccessResult();
            }

            return ResultUtility.FailureResult("导购身份不存在!");
        }

        /// <summary>
        /// 查看导购门店是否有效
        /// url: /scrm/store/guidestoreisok
        /// params: mobile, usecode
        /// </summary>
        [HttpGet]
        public string GuideStoreIsOk(string mobile, string usecode)
        {
            string sql = @"select keyid,wxid from Sys_ShoppingGuide(nolock) where mobile = @mobile";

            var user = db.Crm.Query<dynamic>(sql, new { mobile }).FirstOrDefault();

            if (user != null)
            {
                int userid = user.keyid;

                sql = @"select COUNT(1) from Sys_ShoppingGuideDtl(nolock) as t1
                    inner join Sys_V_Dealer(nolock) as t2 on t2.KeyId = t1.SKeyid
                    where t1.MKeyid = @userid and t2.Usecode = @usecode";

                int count = db.Crm.Query<int>(sql, new { userid, usecode }).FirstOrDefault();

                if (count == 0)
                {
                    return ResultUtility.FailureResult("门店身份已经被移除!");
                }

                return ResultUtility.SuccessResult();
            }

            return ResultUtility.FailureResult("导购身份不存在!");
        }
    }
}